package com.wl.blog.back.service.impl;

import com.wl.blog.back.bean.Article;
import com.wl.blog.back.bean.Category;
import com.wl.blog.back.bean.Tag;
import com.wl.blog.back.mapper.ArticleMapper;
import com.wl.blog.back.mapper.CategoryMapper;
import com.wl.blog.back.mapper.TagMapper;
import com.wl.blog.back.service.ArticleService;
import com.wl.blog.base.exception.BlogEnum;
import com.wl.blog.base.exception.BlogException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @创建人 万磊
 * @创建时间 2021/12/5
 * 好好学习，天天向上
 */
@Service
public class ArticleServiceImpl  implements ArticleService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private TagMapper tagMapper;

    @Override
    public List<Article> list(String uid, String title) {
        Example example = new Example(Article.class);
        Example.Criteria criteria = example.createCriteria();
        //查询当前登录用户的文章
        criteria.andEqualTo("uid",uid);
        if (title != null && !title.equals("")){
            criteria.andLike("title","%"+title+"%");
        }
        List<Article> articles = articleMapper.selectByExample(example);
        //遍历所有文章
        for (Article article : articles) {
            String cid = article.getCid();
            //滚局cid查询栏目表，查询栏目对象
            Category category = categoryMapper.selectByPrimaryKey(cid);

            article.setCid(category.getCname());
        }
        return articles;
    }

    @Override
    public void isOpen(Article article) {
        int count = articleMapper.updateByPrimaryKeySelective(article);
        if (count == 0){
            throw new BlogException(BlogEnum.ARTICLE_ISOPEN);
        }
    }

    @Override
    public List<Category> queryCategory() {
        return categoryMapper.selectAll();
    }

    @Override
    public List<Tag> queryTags(String cid) {
        Tag tag = new Tag();
        tag.setCid(cid);
        return tagMapper.select(tag);
    }

}
